package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.article.service.CollectionBehaviorService;
import com.heima.common.constants.BehaviorConstants;
import com.heima.common.redis.CacheService;
import com.heima.model.behavior.dtos.CollectionBehaviorDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.thread.ApUserThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class CollectionBehaviorServiceImpl implements CollectionBehaviorService {

    @Autowired
    private CacheService cacheService;

    /**
     * 文章收藏与取消收藏
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult collectionBehavior(CollectionBehaviorDto dto) {
        // 参数校验
        if (dto == null || dto.getEntryId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        // 判断是否是登录状态
        ApUser user = ApUserThreadLocalUtil.getUser();
        if (user == null || user.getId() == 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        // 设置key
        String key = BehaviorConstants.COLLECTION_BEHAVIOR + dto.getEntryId();

        // 判断用户当前操作是收藏还是取消收藏
        if (dto.getOperation() == 0) {
            // 收藏       key     当前登录id      dto数据
            cacheService.hPut(key, user.getId().toString(), JSON.toJSONString(dto));
            return ResponseResult.okResult(200, "收藏成功!");
        } else {
            cacheService.hDelete(key, user.getId().toString());
            return ResponseResult.okResult(200, "取消收藏成功!");
        }
    }
}
